package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.constant.AppConstant;
import org.example.pojo.entity.TbUser;
import org.example.exception.UserException;
import org.example.mapper.TbUserMapper;
import org.example.pojo.entity.User;
import org.example.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;


@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public TbUser login(User user) {
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUsername, user.getUsername());
        TbUser tbUserDB = this.getOne(queryWrapper);
        if (tbUserDB == null) {
            throw new UserException(AppConstant.LOGIN_USER_NOT_EXIST);
        }
        //用户名去数据库查询
        if (tbUserDB.getUsername() == null) {
            throw new RuntimeException(AppConstant.LOGIN_PASSWORD_ERR);
        }
        //判断用户名
        //判断密码
        if (!tbUserDB.getPassword().equals(user.getPassword())) {
            throw new RuntimeException(AppConstant.LOGIN_PASSWORD_ERR);
        }
        //判断用户状态
        if (tbUserDB.getStatus().equals(TbUser.USER_STATUS_UNABLE)) {
            throw new RuntimeException(AppConstant.LOGIN_USER_DISABLE);
        }
        //存redis
        redisTemplate.opsForValue().set(user.getUsername(), user.getPassword() );
        return tbUserDB;
    }

    /**
     * 用户注册
     */
    @Override
    public void registerUser(User user) {
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUsername,user.getUsername());
        TbUser tbUser = this.getOne(queryWrapper);
        if (!StringUtils.isEmpty(tbUser)){
            throw new UserException(AppConstant.LOGIN_USERNAME_EXIST);
        }
        //插入注册用户信息
        TbUser insertUser = new TbUser();
        insertUser.setPassword(user.getPassword());
        insertUser.setUsername(user.getUsername());
        insertUser.setStatus(TbUser.USER_STATUS_ABLE);
        this.save(insertUser);
    }
}
